package com.lx.wx.restful.wechat;

import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.domain.vo.wcategory.WCategoryVo;
import com.lx.pc.domain.vo.worder.WOrderVo;
import com.lx.pc.domain.vo.wordercategory.WOrderCategoryVo;
import com.lx.pc.domain.vo.wpricetemplate.WPricetemplateVo;
import com.lx.pc.domain.vo.wx.WeixinVo;
import com.lx.pc.service.user.IUserService;
import com.lx.pc.service.wcategory.IWCategoryService;
import com.lx.pc.service.worder.IWOrderService;
import com.lx.pc.service.worderCategory.IWOrderCategoryService;
import com.lx.pc.service.wpricetemplate.IWPricetemplateService;
import com.lx.pc.service.wx.IWeixinService;
import com.lx.pc.utils.Constants;
import com.lx.pc.utils.OmsPage;
import com.lx.wx.restful.utils.AjaxResult;
import com.lx.wx.restful.utils.TemplateData;
import com.lx.wx.restful.utils.WeiXinUtils;

/**
 * 用户
 * @author houzhong
 */
@Controller
@RequestMapping("/wx")
public class UserController {

	/**
	 * 微信获取token
	 */
	@Resource(name = "weixinService")
	private IWeixinService weixinService;
	
	/**
	 * 分类
	 */
	@Resource(name = "wCategoryService")
	private IWCategoryService wCategoryService;
	
	/**
	 * 用户
	 */
	@Resource(name = "userService")
	private IUserService userService;
	
	/**
	 * 用户订单
	 */
	@Resource(name = "wOrderService")
	private IWOrderService wOrderService;
	
	/**
	 * 用户多个分类多个重量
	 */
	@Resource(name = "wOrderCategoryService")
	private IWOrderCategoryService wOrderCategoryService;
	
	/**
	 * 参考价模版
	 */
	@Resource(name = "wPricetemplateService")
	private IWPricetemplateService wPricetemplateService;

	/**
	 * 进入首页
	 * @return
	 */
	@RequestMapping("/toWxClientHome")
	public ModelAndView toWxClientHome(HttpServletRequest request,UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/home");
		
		String code = request.getParameter("code");
		System.out.println("home:code--------" + code);
		
		//获取公众号信息
		JSONObject jsonObject = WeiXinUtils.getUserInfo(code);
		
		//获取用户信息
		UserVo userVo = getOpenId(jsonObject);
		//UserVo userVo = userService.findByUsername(v);
		//获取分类
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		
		mv.addObject("listCategory",listCategory);
		mv.addObject("userVo",userVo);
		return mv;
	}
	
	/**
	 * 单独跳转到首页
	 * @param v
	 * @return
	 */
	@RequestMapping("/toHome")
	public ModelAndView toHome(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/home");
		UserVo userVo = userService.findByUsername(v);
		//获取分类
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		
		mv.addObject("listCategory",listCategory);
		mv.addObject("userVo",userVo);
		
		return mv;
	}
	
	/**
	 * 查看服务条款
	 */
	@RequestMapping("/toService")
	public ModelAndView toService(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/order/serviceAgreement");
		UserVo userVo = userService.findByUsername(v);
		//获取分类
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		
		mv.addObject("listCategory",listCategory);
		mv.addObject("userVo",userVo);
		return mv;
	}
	
	/**
	 * 进入参考价
	 */
	@RequestMapping("/toReferencePrice")
	public ModelAndView toReferencePrice(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/order/referencePrice");
		//参考价模版
		WPricetemplateVo pricetemplateVo = wPricetemplateService.findByWPriceTemplate();
		
		mv.addObject("userVo",v);
		mv.addObject("pricetemplateVo",pricetemplateVo);
		return mv;
	}
	
	/**
	 * 进入下单页
	 */
	@RequestMapping("/toOrder")
	public ModelAndView toOrder(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/order/order");
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		UserVo userVo = userService.findByUsername(v);
		
		mv.addObject("userVo",userVo);
		mv.addObject("listCategory",listCategory);
		return mv;
	}
	
	/**
	 * 进入添加地址页
	 */
	@RequestMapping("/toAddress")
	public ModelAndView toAddress(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/client/order/add_address");
		UserVo userVo = userService.findByUsername(v);
		mv.addObject("userVo",userVo);
		return mv;
	}
	
	/**
	 * 添加地址
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toSaveAddress.do")
	public AjaxResult<String> toSaveAddress(UserVo v){
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		UserVo userVo = userService.find(v.getId());
		userVo.setProvince("江苏省");
		//区
		userVo.setCity(v.getCity().replaceAll(" ", ""));
		//街道
		userVo.setArea(v.getArea().replaceAll(" ", ""));
		userVo.setAddress(v.getAddress());
		userVo.setContacts(v.getContacts());
		userVo.setTelephone(v.getTelephone());
		if (userVo.getArea() != null) {
			UserVo user = new UserVo();
			user.setArea(userVo.getArea());
			user.setWxType(3);
			List<UserVo> userVos = userService.findByUser(user);
			if (userVos.size()>0 ) {
				userService.updateUser(userVo);
				ajaxResult.setMsg("1");
			}else {
				ajaxResult.setMsg("2");
			}
		}
		return ajaxResult;
	}
			
	/**
	 * 
	 * @param 下单成功
	 * @param categoryStr
	 * @param weightStr
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toAdd.do")
	public AjaxResult<String> toAdd(WOrderVo v,@RequestParam(value = "categoryStr[]")String[] categoryStr,@RequestParam(value = "weightStr[]")String[] weightStr){
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		UserVo userVo = new UserVo();
		userVo.setId(new BigInteger(v.getUserId()));
		UserVo user = userService.findByUsername(userVo);
		//设置订单编号
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String time = df.format(new Date());
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 1000000;
		
		v.setOrderNumber(time+rannum);
		//根据用户发单地区分配给相同地区商家
		
		UserVo userVo2 = new UserVo();
		if (user.getArea() != null) {
			
			userVo2.setArea(user.getArea());
			userVo2.setWxType(3);
			List<UserVo> userVos = userService.findByUser(userVo2);
			if (userVos.size()>0 ) {
				//接单人
				v.setReceiptId(userVos.get(0).getbId());
			}
		}
		
		v.setProvince(user.getProvince());
		v.setCity(user.getCity());
		v.setArea(user.getArea());
		v.setAddress(user.getAddress());
		//判断当前区域是否有商家
		if (v.getReceiptId() != null) {
			//进行中
			v.setStatus(1);
		}else {
			//无人接单
			v.setStatus(4);
		}
		
		wOrderService.save(v);
		
		//发送消息模版使用的分类属性
		String category = "";
		if (categoryStr != null) {
			for (int i = 0 ;i<categoryStr.length; i++) {
				WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
				orderCategoryVo.setwCategoryId(categoryStr[i]);
				orderCategoryVo.setWeight(weightStr[i]);
				//订单编号
				orderCategoryVo.setOrderNumber(v.getOrderNumber());
				orderCategoryVo.setActualWeight("");
				
				WCategoryVo categoryVo = new WCategoryVo();
				categoryVo.setCategoryId(categoryStr[i]);
				List<WCategoryVo> categoryVos = wCategoryService.findByWCategory(categoryVo);
				category += categoryVos.get(0).getName() +":"+weightStr[i] + "\r\n" ;
				wOrderCategoryService.save(orderCategoryVo);
			}
		}
		
		//获取微信token
		WeixinVo weixinVo = weixinService.findByWeixin();
		//查询回收员名称和电话
		BigInteger reId = new BigInteger(v.getReceiptId());
		UserVo vo = userService.find(reId);
		//发送消息模版
		Map<String,TemplateData> param = new HashMap<>();
        param.put("first",new TemplateData("订单已受理","#696969"));
        param.put("OrderSn",new TemplateData(v.getOrderNumber(),"#696969"));
        param.put("OrderStatus",new TemplateData("已受理","#696969"));
		param.put("remark",new TemplateData("预约时间："+v.getPickTime()+" \r\n"
	        		+ "回收员："+vo.getContacts()+" \r\n"
	        		+ "回收员电话："+vo.getTelephone()+" \r\n"
	        		+category
	        		+ "请提前与回收员联系 \r\n","#696969"));
		
        //调用发送微信消息给用户的接口
        WeiXinUtils.sendWechatMsgToUser(weixinVo.getAccessToken(),user.getWxOpenId(),Constants.TEMPLATE, "", "#000000", WeiXinUtils.packJsonmsg(param));
        
        //发送消息模版
  		Map<String,TemplateData> par = new HashMap<>();
  		par.put("first",new TemplateData("接单啦","#696969"));
  		par.put("tradeDateTime",new TemplateData(v.getCreateTime(),"#696969"));
  		par.put("orderType",new TemplateData("进行中","#696969"));
  		par.put("customerInfo",new TemplateData(user.getContacts(),"#696969"));
  		par.put("orderItemName",new TemplateData("联系电话","#696969"));
  		par.put("orderItemData",new TemplateData(user.getTelephone(),"#696969"));
  		par.put("remark",new TemplateData(category 
  				+"预约时间："+v.getPickTime()+" \r\n"
  				+ "请提前与用户联系 \r\n","#696969"));
  		//调用发送微信消息给回收员的接口
        WeiXinUtils.sendWechatMsgToReceipt(weixinVo.getAccessToken(),vo.getWxOpenId(),Constants.RECEIPT, "", "#000000", WeiXinUtils.packJsonmsg(par));
		ajaxResult.setMsg("1");
		return ajaxResult;
	}
	
	/**
	 * 查询当前用户所有订单
	 * @param request
	 * @param id
	 * @param status
	 * @return
	 */
	@RequestMapping("/toOrderList")
	public ModelAndView toOrderList(HttpServletRequest request,String id,Integer status) {
		ModelAndView mv = new ModelAndView("/wx/client/order/order_list");
		 UserVo userVo = new UserVo();
		if (id != null) {
			userVo.setId(new BigInteger(id));
			userVo = userService.findByUsername(userVo);
		}else {
			String code = request.getParameter("code");
			System.out.println("order:code--------" + code);
			//获取公众号信息
			JSONObject jsonObject = WeiXinUtils.getUserInfo(code);
			//获取用户信息
			userVo = getOpenId(jsonObject);
		}
		
		mv.addObject("userVo",userVo);
		
		return mv;
	}
	
	/**
	 * 获取当前用户的订单
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/serchOrderList")
    @ResponseBody
    public  String serchOrderList(WOrderVo v,Integer page,Integer size) throws IOException {
        Map<String,Object> result = new HashMap<String, Object>();
		OmsPage<WOrderVo> pages = wOrderService.findByWOrder(v, page, size);
		if (pages.getResult().size()>0) {
			for (WOrderVo orderVo : pages.getResult()) {
				WOrderCategoryVo categoryVo = new WOrderCategoryVo();
				categoryVo.setOrderNumber(orderVo.getOrderNumber());
				categoryVo.setUserId(orderVo.getUserId());
				WOrderCategoryVo vo = wOrderCategoryService.findBySumPrice(categoryVo);
				if (vo != null) {
					//总价
					orderVo.setCountPrice(vo.getPrice());	
				}
			}
		}
		
        result.put("wOrderVo", pages.getResult());
        result.put("pages", pages);
        
        return JSON.toJSONString(result);
	}
	
	/**
	 * 修改订单状态
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/updateOrder")
    @ResponseBody
    public  AjaxResult<String> updateOrder(WOrderVo v) throws IOException {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		WOrderVo orderVo = wOrderService.find(new BigInteger(v.getbId()));
		orderVo.setStatus(v.getStatus());
		String flag = wOrderService.updateStatus(orderVo);
		ajaxResult.setMsg(flag);
		return ajaxResult;
	}
	
	/**
	 * 验证openid 是否存在，不存在新增
	 * @param jsonObject
	 * @return
	 */
	public UserVo getOpenId(JSONObject jsonObject) {
		//获取openid
		String openId = jsonObject.getString("openid");
		
		System.out.println("openid-------" + openId);
		UserVo user = new UserVo();
		user.setWxOpenId(openId);
		user.setWxType(1);
		user = userService.findByUsername(user);
		if (user == null ) {
			user = new UserVo();
			user.setWxOpenId(openId);
			user.setWxType(1);
			user.setStatus(1);
			user.setAuditStatus(3);
			userService.save(user);
		}
		return user;
	}
}
